package com.sheng.center.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.sheng.center.entity.User;

public class UserDaoImpl implements UserDao{

	private SessionFactory sessionFactory;
	
	public boolean register(User user) {
		try {
			sessionFactory.getCurrentSession().save(user);
			return true;
		} catch (HibernateException e) {
			return false;
		}
	}
	
	@Override
	public void edit(User user) {
		sessionFactory.getCurrentSession().update(user);
	}
	public User login(User user) {
		User u = null;
		u = (User)sessionFactory.getCurrentSession().createQuery("from User where username=:username and password=:password and isUser=:isUser")
		.setString("username", user.getUsername())
		.setString("password", user.getPassword())
		.setInteger("isUser", user.getIsUser()).uniqueResult();
		return u;
	}
	
	@Override
	public List<User> findAllList(User model) {
		String hql = "from User where 1=1 ";
		if(null != model.getUsername()){
			hql = hql + " and username like '%"+model.getUsername()+"%'";
		}
		Query query = sessionFactory.getCurrentSession().createQuery(hql);  
        List list = query.list();  
        return list;
	}
	public User findById(User user) {
		Query query = sessionFactory.getCurrentSession().createQuery("from User where id='"+user.getId()+"'");  
		List list = query.list();  
		if (null != list && 0 < list.size()) {
			user = (User) list.get(0);
		}
		return user;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	
}
